package com.dms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.dms.bean.Student;
import com.dms.bean.Student;
import com.dms.util.DBUtil;


public class StudentDao {  //增删查改
	private static DBUtil	db	= new DBUtil();
	public static boolean add(Student studentdent) {
		boolean val = false;
		if (studentdent!=null) {
			String sql = "insert into student (stuID,name,password,dormID) values(?,?,?,?)";
			try {
				db.update(sql,studentdent.getStuID(), studentdent.getName(), studentdent.getPassword(), studentdent.getDormID());
				val=true;
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			try {
				db.close();
			}
			catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return val;
	}
	
	public static ArrayList<Student> list() {
		ArrayList<Student> students = new ArrayList<Student>();
		String sql = "select * from student";
		try {
			ResultSet rs = db.query(sql);
			while (rs.next()) {
				students.add(new Student(rs.getString("stuID"), rs.getString("name"), rs.getString("password"), rs.getString("dormID")));
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		try {
			db.close();
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		return students;
	}
	public static Student find(String stuID) {
		Student student = new Student();
		String sql = "select dormID,name,password from student where stuID =?";
		try {
			ResultSet rs = db.query(sql, stuID);
			boolean val = (rs != null && rs.next()) ? true : false;
			if (val){
				student.setDormID(rs.getString("dormID"));
				student.setStuID(stuID);
				student.setName(rs.getString("name"));
				student.setPassword(rs.getString("password"));
			}
				
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		try {
			db.close();
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		return student;
	}
	
	public static boolean save(Student student) throws Exception {
		boolean var = false;
		try {
			if (student != null) {
				String sql = "update student set name=?,password=?,dormID=? where stuID =?";
				db.update(sql, student.getName(), student.getPassword(), student.getDormID(), student.getStuID());
				var = true;
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		try {
			db.close();
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		return var;
	}
	public static boolean delete(String stuID) {
		boolean var = false;
		try {
				String sql = "delete from student where stuID =?";
				db.update(sql, stuID);
				var = true;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		try {
			db.close();
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		return var;
	}
}
